from flask import Blueprint, request, jsonify
import json
from utils.db import db1
from view.compan import get_data
from utils.redison import r

bp_work = Blueprint('work', __name__)

import json


@bp_work.route('/work', methods=['PUT', 'GET'])
def work():
    if request.method == 'PUT':
        data = get_data()
        list = json.loads(data["list"])
        print(list)
        sql = 'update yewu set params = "%s" where id = %d' % (list, int(data['id']))
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = request.args.get('id')
        if not id:
            sql = 'select * from yewu'
            res = db1.findall(sql)
            return jsonify({'code': 200, 'list': res})
        else:
            sql = 'select * from yewu where id = %d' % (int(id))
            res = db1.findone(sql)
            return jsonify({'code': 200, "list": res})


# 获取数据源
@bp_work.route('/source', methods=['GET'])
def source():
    if request.method == 'GET':
        value = r.get_str('datasource')
        if value:
            list = eval(value)
        else:
            sql = 'select * from tablename'
            res = db1.findall(sql)
            list = []
            if res:
                for i in res:
                    dict = {"id": i["id"], "name": i["name"]}
                    sql1 = 'select id,name,type from %s' % (i["tablen"])
                    res1 = db1.findall(sql1)
                    dict['son'] = res1
                    list.append(dict)
            r.set_str('datasource', json.dumps(list))
        return jsonify({"code": 200, 'list': list})


@bp_work.route('/holiday', methods=['GET', 'POST'])
def holiday():
    if request.method == 'GET':
        id = int(request.args.get('id'))
        print(id)
        sql = 'select * from yewu where id = %d' % (id)
        res = db1.findone(sql)
        list = eval(res['params'])
        res['params'] = list
        return jsonify({'code': 200, 'list': res})

    elif request.method == 'POST':
        data = request.form.to_dict()
        list = eval(data['zhiwu'])
        list1 = sorted(list)
        nextroleid = list1[0]
        list2 = str(list1)

        sql = """
            insert into tasktable(id,title,params,status,roleid,userid,nextroleid,yewuid) value(0,'%s','%s',1,'%s',%d,%d,%d)
        """ % (data['title'], data['params'], list2, int(data['userid']), int(nextroleid), int(data['yewuid']))

        db1.update(sql)
        sql1 = """select id,title from tasktable where title = '%s'""" % (data['title'])
        res1 = db1.findone(sql1)
        print(res1)
        key = "task%d" % (int(nextroleid))
        r.hash_set(key, str(res1['id']), str(res1['title']))
        return jsonify({'code': 200})


@bp_work.route('/task', methods=['POST', 'GET'])
def task():
    if request.method == 'GET':
        userid = request.args.get('id')
        sql = """select * from tasktable where userid = %d""" % (int(userid))
        res = db1.findall(sql)
        for i in res:
            params = eval(i['params'])
            i['params'] = params
        return jsonify({'code': 200, "list": res})


@bp_work.route('/ptask', methods=['GET'])
def ptask():
    if request.method == 'GET':
        userid = request.args.get('id')
        key = "task%d" % (int(userid))
        ptask = r.get_all(key)
        list = []
        for i, j in ptask.items():
            id = str(i, encoding='utf8')
            title = str(j, encoding='utf8')
            list.append({'id': id, 'title': title})
        print(list)
        return jsonify({'code': 200, 'list': list})


@bp_work.route('/taskinfo', methods=['GET', 'POST'])
def taskinfo():
    if request.method == 'GET':
        id = request.args.get('id')
        sql = """select * from tasktable where id = %d""" % (int(id))
        res = db1.findone(sql)
        sql2 = """select * from apptask where taskid = %d""" % (int(id))
        task = db1.findall(sql2)
        res['params'] = eval(res['params'])
        res['apptask'] = task
        return jsonify({'code': 200, 'list': res})
    elif request.method == 'POST':
        data = get_data()
        print(data)
        sql2 = """select * from tasktable where id = %d""" % (int(data['taskid']))
        res2 = db1.findone(sql2)
        list = eval(res2['roleid'])
        nextroleid = 0
        for i in range(len(list)):
            if list[i] == int(data['userid']):
                index = i + 1
                try:
                    nextroleid = list[index]
                except Exception as e:
                    nextroleid = 0
                break
        if int(data['decision']) == 1:
            sql1 = """insert into apptask(taskid,shenpiid,decision,content,username) values(%d,%d,%d,"%s","%s")""" % (
                int(data['taskid']), int(data['userid']), int(data['decision']), data['content'], data['username'])
            db1.update(sql1)

            if nextroleid == 0:

                sql4 = """update tasktable set status = 3,nextroleid = %d where id = %d""" % (
                    nextroleid, int(data['taskid']))
                db1.update(sql4)
                k = "task%d" % (int(data['userid']))
                r.del_hash(k, (str(res2['id'])))
                key = "task%d" % (int(nextroleid))
                r.hash_set(key, str(res2['id']), str(res2['title']))
            else:
                sql4 = """update tasktable set status = 2,nextroleid = %d where id = %d""" % (
                    nextroleid, int(data['taskid']))
                db1.update(sql4)
                k = "task%d" % (int(data['userid']))
                r.del_hash(k, (str(res2['id'])))
                key = "task%d" % (int(nextroleid))
                r.hash_set(key, str(res2['id']), str(res2['title']))
        else:
            sql1 = """insert into apptask(taskid,shenpiid,decision,content,username) values(%d,%d,%d,"%s","%s")""" % (
                int(data['taskid']), int(data['userid']), int(data['decision']), data['content'], data['username'])
            db1.update(sql1)
            if list.index(int(data['userid'])) == 0:
                sql4 = """update tasktable set status = 1,nextroleid = 0 where id = %d""" % (int(data['taskid']))
                db1.update(sql4)
                sql2 = """select * from tasktable where id = %d""" % (int(data['taskid']))
                res2 = db1.findone(sql2)
                k = "task%d" % (int(data['userid']))
                r.del_hash(k, (str(res2['id'])))
            else:
                ind = list.index(int(data['userid'])) - 1
                nextroleid = list[ind]

                sql4 = """update tasktable set status = 2,nextroleid = %d where id = %d""" % (
                    nextroleid, int(data['taskid']))
                db1.update(sql4)
                k = "task%d" % (int(data['userid']))
                r.del_hash(k, (str(res2['id'])))
                key = "task%d" % (int(nextroleid))
                r.hash_set(key, str(res2['id']), str(res2['title']))

        return jsonify({'code': 200})


# 修改审核失败的
@bp_work.route('/puttask', methods=['GET', 'PUT'])
def puttask():
    if request.method == 'GET':
        id = request.args.get('id')
        print(id)
        sql1 = """select * from tasktable where id = %d""" % (int(id))
        res1 = db1.findone(sql1)
        res1['params'] = eval(res1['params'])
        res1['roleid'] = eval(res1['roleid'])
        return jsonify({'code': 200, 'list': res1})
    elif request.method == 'PUT':
        data = get_data()
        print(data)
        list = data['roleid']
        list1 = sorted(list)
        nextroleid = list1[0]
        list2 = str(list1)
        sql = """update tasktable set title = '%s',params = '%s',status = 1,roleid = '%s',userid = %d,nextroleid = %d,yewuid = %d where id = %d""" % (
            data['title'], data['params'], list2, int(data['userid']), int(nextroleid), int(data['yewuid']),int(data['id']))
        # sql = """
        #             insert into tasktable(id,title,params,status,roleid,userid,nextroleid,yewuid) value(0,'%s','%s',1,'%s',%d,%d,%d)
        #         """ % (data['title'], data['params'], list2, int(data['userid']), int(nextroleid), int(data['yewuid']))
        print(sql)
        db1.update(sql)
        sql1 = """select id,title from tasktable where title = '%s'""" % (data['title'])
        res1 = db1.findone(sql1)
        print(res1)
        key = "task%d" % (int(nextroleid))
        r.hash_set(key, str(res1['id']), str(res1['title']))
        return jsonify({'code': 200})
